#pragma once
#include <string>
#include "Init.hpp"
#include "log.hpp"
using namespace std;

Init init;
class Task
{
public:
  Task(int sockfd, const std::string &clientip, const uint16_t &clientport)
      : _sockfd(sockfd), _clientip(clientip), _clientport(clientport)
  {
  }

  void run()
  {
    char buffer[4096];

    ssize_t n = read(_sockfd, buffer, sizeof(buffer));
    if (n > 0)
    {
      buffer[n] = 0;
      std::cout << "Client say# " << buffer << std::endl;

      std::string message = init.translation(buffer);

      n = write(_sockfd, message.c_str(), message.size());
      if (n < 0)
      {
        lg(Error, "write Error..., errno: %d, errmsg: %s", errno, strerror(errno));
      }
    }
    else if (n == 0)
    {
      lg(Info, "%s:%d, server quit sockfd: %d", _clientip.c_str(), _clientport, _sockfd);
    }
    else
    {
      lg(Error, "read Error..., errno: %d, errmsg: %s", errno, strerror(errno));
    }

    close(_sockfd);
  }

  void operator()()
  {
    run();
  }

  ~Task()
  {
  }

private:
  int _sockfd;
  std::string _clientip;
  uint16_t _clientport;
};
